package Login;
import java.io.IOException;
import java.sql.PreparedStatement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import Utils.Constant;
import Utils.DbAccess;
import Utils.MD5;
import Utils.ZipResponse;



public class DoLogin extends HttpServlet {

	private static final long serialVersionUID = 1L;
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
		throws ServletException, IOException {
//		process(req, resp);
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
		throws ServletException, IOException {
	
		proccess(req, resp);
	}
	
	private void proccess(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
		req.setCharacterEncoding("UTF-8");
		res.setCharacterEncoding("UTF-8");
		res.setContentType("text/xml");
		String 	xml = "<root value='false'/>";
		String action=req.getParameter("act");
		
		
		
		DbAccess db = null;
		
		try{
			if(action.equals("login")){
				String username = req.getParameter("username");
				String password="";
				try{
					password = MD5.encrypt(req.getParameter("password"));
				}
				catch (Exception e) {
					ZipResponse.write(req, res, xml, "UTF-8");
					return;
				}
				db = new DbAccess();
				db.connectTemp("localhost", Constant.DB);
				String sql = "Select  * from account where username=? and password=?";
				db.stmt = db.conn.prepareStatement(sql);
				
				db.stmt.setString(1, username);
				db.stmt.setString(2, password);
				
				db.rs = db.stmt.executeQuery();
				if(db.rs.next()){
					HttpSession session = req.getSession();
					session.setAttribute("userid", username);
					session.setAttribute("usertype", db.rs.getInt("type"));
					session.setMaxInactiveInterval(60*360);
					xml = "<root value='true'/>";
					db.stmt.close();
					sql = "UPDATE account SET lastlogin=now() WHERE username=?";
					db.stmt = db.conn.prepareStatement(sql);
					db.stmt.setString(1, username);
					db.stmt.executeUpdate();
				}
			}else if(action.equals("checklogin")){
				Object obj_userid = req.getSession().getAttribute("userid");
				Object obj_usertype = req.getSession().getAttribute("usertype");
				if(obj_userid!=null){
					
					xml =  "<root value='true' utype='"+obj_usertype.toString()+"' uid='"+obj_userid.toString()+"'/>";
				}else{
					
					xml =  "<root value='false'/>";
				}
			}
		}catch (Exception e) {
			xml = "<root value='false'/>";
			e.printStackTrace();
		}finally{
			if(db!=null)db.DBClose();
		}
		
		ZipResponse.write(req, res, xml, "UTF-8");
	
	}
}
